package com.jwater.core.manager.master.check;

import com.jwater.core.manager.common.conf.CoreConfParse;
import com.jwater.core.manager.master.MasterNodeImpl;
import com.jwater.core.manager.proxy.ProxyManager;
import com.jwater.launch.HomePath;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;

/**
 * @description:
 * @author: jnner
 * @createDate: 2021/3/6
 * @version: 1.0
 */
public class CoreConfCheck implements Runnable {
    protected static Logger logger = LoggerFactory.getLogger(CoreConfCheck.class);
    private Thread thread;
    private long lastUpdateTime = -1;
    private int masterId;
    private MasterNodeImpl masterNode;

    public CoreConfCheck(int masterId, MasterNodeImpl masterNode) {
        this.masterId = masterId;
        this.masterNode = masterNode;
    }

    public void start() {
        thread = new Thread(this);
        thread.start();
    }

    @Override
    public void run() {
        while (true) {
            try {
                check();
            } catch (Exception e) {
                logger.error(e.toString(), e);
            }
            synchronized (this) {
                try {
                    this.wait(1000);
                } catch (InterruptedException e) {
                    logger.error(e.toString(), e);
                }
            }
        }
    }

    private void check() {
        File file = new File(HomePath.getConfPath(), "jwater.core.xml");
        if (!file.exists()) {
            logger.error("can not find file:" + file);
        }
        if (lastUpdateTime == -1) {
            lastUpdateTime = file.lastModified();
            return;
        }
        if (file.lastModified() != lastUpdateTime) {
            logger.info("jwater.core.xml update...");
            CoreConfParse coreConf = new CoreConfParse();
            coreConf.parse();
            ProxyManager proxyManager = new ProxyManager(coreConf.getProxyInfos());
            proxyManager.setMasterId(masterId);
            proxyManager.start(coreConf);
            ProxyManager oldProxyManager = masterNode.proxyManager;
            masterNode.coreConf = coreConf;
            masterNode.proxyManager = proxyManager;
            if (oldProxyManager != null) {
                oldProxyManager.close();
            }
            lastUpdateTime = file.lastModified();
        }
    }
}
